import psutil
import re
import socket
def get_third_octet(interface_name):
    for interface, addrs in psutil.net_if_addrs().items():
        if interface == interface_name:
            for addr in addrs:
                if addr.family == socket.AF_INET:
                    ip = addr.address
                    octets = ip.split('.')
                    return octets[2]
    return None

def update_ssh_config(file_path, third_octet):
    # 读取配置文件内容
    with open(file_path, 'r') as file:
        lines = file.readlines()

    # 新的配置内容
    new_config = f"""Host Ubuntu24.04
    HostName 192.168.{third_octet}.128
    User kevin
    Port 22"""

    # 写入新的配置内容
    with open(file_path, 'w') as file:
        file.write(new_config)

# 使用VMware Network Adapter VMnet8作为接口名称

interface_name = 'VMware Network Adapter VMnet8'
third_octet = get_third_octet(interface_name)
if third_octet:
    print(f"The third octet of the IP address for {interface_name} is: {third_octet}")
    config_file_path = "C:\\Users\\1\\.ssh\\config"
    update_ssh_config(config_file_path, third_octet)
    print(f"SSH config file has been updated with the third octet: {third_octet}")
else:
    print(f"No IP address found for {interface_name}")